package cn.edu.lingnan.controller;

import cn.edu.lingnan.bean.Images;
import cn.edu.lingnan.config.CloudqiniuConfig;
import cn.edu.lingnan.service.image.ImageService;
import cn.edu.lingnan.tools.ResultVo;
import cn.edu.lingnan.tools.ResultVoUtils;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.qiniu.common.QiniuException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/imgs")
public class ImgController {

    @Resource
    ImageService imageService;

    @Resource
    private CloudqiniuConfig cloudqiniuConfig;

    @Value("${saveImage.path}")
    private String path;

    @ResponseBody
    @PostMapping("/uploadFilesImgCloud")
    public ResultVo uploadFilesImgCloud(@RequestParam(value = "file", required = false) MultipartFile file,
                                   HttpServletRequest request) throws IOException {
        System.out.println("进来。。。。。");

        if (ObjectUtil.isNotNull(file) && file.getSize() > 0) {
            //  上传文件的原文件名  /hello.woller.jpg
            String oldFileName = file.getOriginalFilename();
            //获得原文件的后缀名
            String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
            //重命名
            String newFileName = IdUtil.simpleUUID() + suffix;

            //构造流对象
            InputStream inputStream = file.getInputStream();
            String cloudFileName = cloudqiniuConfig.uploadImgQiNiu(inputStream, newFileName);

            return ResultVoUtils.success("文件上传成功", cloudFileName, "图片上传操作");

        } else {
            return ResultVoUtils.error("文件上传失败", "图片上传操作");
        }

    }

    @ResponseBody
    @PostMapping("/uploadFiles")
    public ResultVo uploadFilesImg(@RequestParam(value = "file", required = false) MultipartFile file,
                                   HttpServletRequest request) throws IOException {
        System.out.println("进来。。。。。");

        if (ObjectUtil.isNotNull(file) && file.getSize() > 0) {
            //  上传文件的原文件名  /hello.woller.jpg
            String oldFileName = file.getOriginalFilename();
            //获得原文件的后缀名
            String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
            //重命名
            String newFileName = IdUtil.simpleUUID() + suffix;

            //指定文件存储路径
            String dirUploadImg = path + File.separator + "uploadImg";
            File filePath = new File(dirUploadImg);
            //判断存储图片的目录是否存在，不存在构建
            if (!filePath.exists()) {
                filePath.mkdir();   //构建uploadImg目录
            }
            dirUploadImg = path + File.separator + "uploadImg" + File.separator + newFileName;
            filePath = new File(dirUploadImg);
            file.transferTo(filePath);

            //Object data = filePath;


            return ResultVoUtils.success("文件上传成功", newFileName, "图片上传操作");

        } else {
            return ResultVoUtils.error("文件上传失败", "图片上传操作");
        }

    }

    //public static void main(String[] args) {
    //    File filePath = new File("C:\\jjj.jpg");
    //    if (!filePath.exists()){
    //        System.out.println("0000000000000");
    //        filePath.mkdir();   //构建uploadImg目录
    //    }
    //
    //     filePath = new File("C:\\bbbb\\jjj.jpg");
    //
    //        filePath.mkdirs();   //构建uploadImg目录
    //
    //}


    @PostMapping("/saveImg")
    @ResponseBody
    public ResultVo saveImg(@RequestBody Images img) {

        if (ObjectUtil.isNotNull(img)) {
            imageService.save(img);
            return ResultVoUtils.success("添加图片成功", "添加图片操作");
        } else {
            return ResultVoUtils.error("添加图片失败", "添加图片操作");
        }
    }

    @PostMapping("/showImgLimits")
    @ResponseBody
    public ResultVo showImgLimits(String page, @RequestParam(defaultValue = "10", name = "limit") String limit) {
        Map<String, Object> objectMap = imageService.page(Integer.parseInt(page), Integer.parseInt(limit));
        Long count = (Long) objectMap.get("TotalElements");
        System.out.println(count + "++++++count======TotalEements");
        List<Images> imgList = (List<Images>) objectMap.get("pageContent");

        return ResultVoUtils.success("图片分页查询操作", imgList, "图片流加载", count);
    }


    /**
     * =========编辑============
     * 下面整个控制器
     */

    @PostMapping("/deleteById")
    @ResponseBody
    public ResultVo deleteById(@RequestBody Integer id) throws QiniuException {
        System.out.println(id);
        //根据id查询，拿到要删除文件路径，删除uploadImg 里面对应的文件
        Images img = imageService.findById(id);
        System.out.println(img.getImgPath() + "=======文件路径");

        //获得文件名，对文件名进行切割   http://r56hngetu.hn-bkt.clouddn.com\27eac869f4c2415d9ddc54436b861d40.jpg
        String fileName = img.getImgPath().substring(img.getImgPath().lastIndexOf("\\")+1);
        System.out.println(fileName+"==============fileName");

        //删除 七牛云 里面对应的文件
        cloudqiniuConfig.delete(fileName);

        imageService.deleteById(id);
        return ResultVoUtils.success("根据id删除七牛云图片成功", "根据id删除图片");
    }


    //@PostMapping("/deleteById")
    //@ResponseBody
    //public ResultVo deleteById(@RequestBody Integer id) throws QiniuException {
    //    System.out.println(id);
    //    //根据id查询，拿到要删除文件路径，删除uploadImg 里面对应的文件
    //    Images img = imageService.findById(id);
    //    System.out.println(img.getImgPath() + "=======文件路径");
    //    String imgPath = path + File.separator + "uploadImg" + File.separator + img.getImgPath();
    //    //删除uploadImg 里面对应的文件
    //    cloudqiniuConfig.delete(img.getImgName());
    //    File file = new File(imgPath);
    //    if (file.isFile() && file.exists()) {
    //
    //
    //
    //
    //        // file.delete();
    //        imageService.deleteById(id);
    //    } else {
    //        return ResultVoUtils.error("根据id删除图片失败", "根据id删除图片");
    //    }
    //
    //    return ResultVoUtils.success("根据id删除图片成功", "根据id删除图片");
    //}



    @DeleteMapping("/deleteBatch")
    @ResponseBody
    public ResultVo deleteBatch(@RequestBody String[] ids) {
        Integer[] integers = Arrays.asList(ids).stream().map(id -> {
            return Integer.parseInt(id);
        }).collect(Collectors.toList()).toArray(new Integer[]{});

        for (int id : integers) {
            //根据id查询，拿到要删除文件路径，删除uploadImg 里面对应的文件
            Images img = imageService.findById(id);
            System.out.println(img.getImgPath() + "=======文件路径");
            String imgPath = path + File.separator + "uploadImg" + File.separator + img.getImgPath();
            //删除uploadImg 里面对应的文件
            File file = new File(imgPath);
            if (file.isFile() && file.exists()) {
                file.delete();
                imageService.deleteById(id);
            }else {
                return ResultVoUtils.error("根据id删除图片失败", "根据id删除图片");
            }
        }

        return ResultVoUtils.success("图片批量删除成功", "图片批量删除操作");
    }


}
